package cn.wenhaha.app.user.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.wenhaha.app.user.service.IUserService;
import cn.wenhaha.common.bean.dto.admin.UserLoginDTO;
import cn.wenhaha.common.bean.dto.admin.UserUpdatePwdDTO;
import cn.wenhaha.common.bean.dto.mapper.UserVoMapper;
import cn.wenhaha.common.bean.vo.UserVo;
import cn.wenhaha.common.db.bean.SysMapping;
import cn.wenhaha.common.db.bean.SysUser;
import cn.wenhaha.common.exception.ApiMSGException;
import org.springframework.stereotype.Service;

/**
 *
 * 用户服务类
 * --------
 *
 * @author ：wyndem
 * @Date ：Created in 2022-03-26 17:04
 */
@Service
public class UserServiceImpl implements IUserService {

    @Override
    public String login(UserLoginDTO loginDTO) {
        SysUser sysUser = SysUser.dao.findByLoginName(loginDTO.getName());
        if(sysUser == null || sysUser.getUserId()==null){
            throw ApiMSGException.build(8000);
        }
        String pwd = SecureUtil.md5(loginDTO.getPwd() + sysUser.getSalt());
        if(!StrUtil.equals(pwd,sysUser.getPassword())){
            throw ApiMSGException.build(8005);
        }
        StpUtil.login(sysUser.getUserId());
        StpUtil.getSession().set("role",sysUser.getRoleCode());
        StpUtil.getSession().set("info",sysUser);
        return   StpUtil.getTokenValue();
    }


    @Override
    public UserVo info(Long id) {
      SysUser sysUser = SysUser.dao.findById(id);
        if(sysUser == null || sysUser.getUserId()==null){
            throw ApiMSGException.build(8000);
        }
        return UserVoMapper.INSTANCE.toBeanSysUser(sysUser);
    }

    @Override
    public boolean checkLogin() {
        try {
            StpUtil.checkLogin();
            return  true;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public SysUser getCurrentUser() {
        return  (SysUser)StpUtil.getSession().get("info");
    }

    @Override
    public boolean updatePwd(UserUpdatePwdDTO updateDTO) {
        Object loginId = StpUtil.getLoginId();
        SysUser sysUser = SysUser.dao.findById(loginId);

        String oldPwd = SecureUtil.md5(updateDTO.getOldPassword() + sysUser.getSalt());

        if (!StrUtil.equals(oldPwd, sysUser.getPassword())){
            throw ApiMSGException.build(8007);
        }
        String pwd = SecureUtil.md5(updateDTO.getPwd() + sysUser.getSalt());
        sysUser.setPassword(pwd);
        sysUser.update();
        StpUtil.logout();
        return true;
    }
}
